#include "dmr_log.h"

#include "stdio.h"


static USART_Module* _USARTx = USART1;

void dmr_logInit(void)
{
	GPIO_InitType GPIO_InitStructure;
    USART_InitType USART_InitStructure;

    RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOA);
    RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO | RCC_APB2_PERIPH_USART1);

    GPIO_Structure_Initialize(&GPIO_InitStructure);
    GPIO_InitStructure.Pin            = GPIO_PIN_9;
    GPIO_InitStructure.GPIO_Mode      = GPIO_MODE_AF_PP;
    GPIO_InitStructure.GPIO_Alternate = GPIO_AF5_USART1;
    GPIO_Peripheral_Initialize(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.Pin             = GPIO_PIN_10;
    GPIO_InitStructure.GPIO_Alternate  = GPIO_AF5_USART1;
    GPIO_Peripheral_Initialize(GPIOA, &GPIO_InitStructure);

    USART_InitStructure.BaudRate            = 115200;
    USART_InitStructure.WordLength          = USART_WL_8B;
    USART_InitStructure.StopBits            = USART_STPB_1;
    USART_InitStructure.Parity              = USART_PE_NO;
    USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
    USART_InitStructure.Mode                = USART_MODE_TX | USART_MODE_RX;
	
	
	NVIC_InitType NVIC_InitStructure;

    /* Enable the USARTy Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel                   = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority           = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Initializes(&NVIC_InitStructure);

    /* init uart */
    USART_Initializes(USART1, &USART_InitStructure);

    /* enable uart */
    USART_Enable(USART1);
	
	USART_Interrput_Enable(_USARTx, USART_INT_RXDNE);
}


void dmr_setLogPort(USART_Module* USART_port)
{
	_USARTx = USART_port;
}


/**
*\*\name    fputc.
*\*\fun     retarget the C library printf function to the USART
*\*\param   ch
*\*\param   f
*\*\return  none
**/
int fputc(int ch, FILE* f)
{
    USART_Data_Send(_USARTx, (uint8_t)ch);
    while (USART_Flag_Status_Get(_USARTx, USART_FLAG_TXDE) == RESET)
        ;

    return (ch);
}


